import { FC, useMemo, useState, useEffect } from "react";

import ThemeContext, { ThemeContextProps } from "./ThemeContext";
import isDarkMode from "../../utils/isDarkMode";

interface ThemeProviderProps {
  theme: string;
}

const ThemeProvider: FC<ThemeProviderProps> = ({ children, theme }) => {
  const initialTheme = useMemo(
    () => (theme === "auto" ? (isDarkMode() ? "dark" : "light") : theme),
    []
  );
  const [currentTheme, setCurrentTheme] = useState(initialTheme);

  useEffect(() => {
    if (theme !== "auto") {
      return;
    }

    const media = window.matchMedia("(prefers-color-scheme: dark)");
    const handler = (e: MediaQueryListEvent) => {
      setCurrentTheme(e.matches ? "dark" : "light");
    };

    media.addEventListener("change", handler);
    return () => media.removeEventListener("change", handler);
  }, []);

  const initialContext: ThemeContextProps = {
    currentTheme,
    setCurrentTheme,
  };

  return (
    <ThemeContext.Provider value={initialContext}>
      {children}
    </ThemeContext.Provider>
  );
};

export default ThemeProvider;
